<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Luo;

class LuoController extends Controller {
    public function __construct() {
        $this->middleware('need_admin_login');
        $this->middleware('need_super_admin');
    }

    public function index() {
        $luo = Luo::paginate(20);
        return view('admin.luo.index', ['luo' => $luo]);
    }

    public function add() {
        if(request()->isMethod('post')){
            $data = request()->all();
            
            $file = request()->file('pic');
            if($file){
                // verify extension
                if(!in_array($file->extension(), ['gif','jpg','png'])){
                    header("HTTP/1.0 500 Invalid extension.");
                }
                $path = $file->store('public/tinymce/' . date('Y/md'));
                $data['pic'] = storage_url($path);
            }
            // check name
            if(Luo::check_name($data['name'])){
                $msg = '此部落名称已存在!';
            }else{
                $luo = Luo::add($data['name'], $data['pic']);
                $luo->set_admin($data['admin_name'], $data['admin_tel']);
                $luo->set_rule($data['guest_min_score']);
                $data = null;
                $msg = '创建成功!';
            }
            return view('admin.luo.add', ['data' => $data, 'msg' => $msg]);
        }
        return view('admin.luo.add');
    }

    public function edit($id) {
        $luo = Luo::findOrFail($id);
        if(request()->isMethod('post')){
            $data = request()->all();
            
            $file = request()->file('pic');
            if($file){
                // verify extension
                if(!in_array($file->extension(), ['gif','jpg','png'])){
                    header("HTTP/1.0 500 Invalid extension.");
                }
                $path = $file->store('public/tinymce/' . date('Y/md'));
                $data['pic'] = storage_url($path);
                $luo->pic = $data['pic'];
            }

            // check name
            if(Luo::check_name($data['name'], $luo->id)){
                $msg = '此部落名称已存在!';
            }else{
                $luo->name = $data['name'];
                $luo->save();
                $luo->set_admin($data['admin_name'], $data['admin_tel']);
                $luo->set_rule($data['guest_min_score']);
                $data = null;
                $msg = '修改成功!';
            }
            return view('admin.luo.edit', ['luo' => $luo, 'data' => $data, 'msg' => $msg]);
        }
        return view('admin.luo.edit', ['luo' => $luo]);
    }

    public function delete($id) {
        $l = Luo::findOrFail($id);
        $l->delete();
    }
}
